import { InjectionKey } from 'vue' // store namespace
import { createStore, useStore, Store } from 'vuex'
import { getToken, setToken, removeToken } from '@/utils/auth'
import { login, getInfo, logout } from '@/api/user'

export interface UserInfo {
  name?: string
}

export interface IState {
  // 如果用户刷新页面vuex状态会消失，再从cookie取token值，添加到vuex中
  token: string;
  roles?: any[];
  userInfo: UserInfo;
}

export const key: InjectionKey<Store<IState>> = Symbol()

const defaultState = (): IState => ({
  token: getToken(),
  userInfo: {}
})

export default createStore<IState>({
  state: defaultState(),
  getters: {
    hasUserInfo(state: IState) {
      return !!Object.keys(state.userInfo || {}).length
    }
  },
  mutations: {
    SET_TOKEN(state: IState, value) {
      state.token = value
    },
    SET_USER_INFO(state: IState, value) {
      state.userInfo = value
    },
    RESET_STATE(state: IState, value) {
      Object.assign(state, defaultState())
    },
  },
  actions: {
    async login({ commit }, params) {
      const { data } = await login(params)
      const { token, isLogin } = data || {}
      if (isLogin) {
        commit('SET_TOKEN', token)
        setToken(token)
      }
      return data
    },

    async getInfo({ commit }) {
      const { data } = await getInfo()
      if (data) {
        commit('SET_USER_INFO', data)
      }
      return !!data
    },

    async logout({ commit }) {
      // const { data } = await logout()
      removeToken()
      commit('RESET_STATE')
      return true
    }
  },
})

export function useUserStore() {
  return useStore(key)
}
